// pkg/errorx/errorx.go
package errorx

var message = map[string]string{}

func init() {
	message = make(map[string]string)
	// 参数相关错误
	message[PARAM_ERROR] = "参数错误"
	message[INVALID_REQUEST] = "无效请求"
	message[MISSING_REQUIRED_FIELD] = "缺少必填字段"

	// 权限相关错误
	message[UNAUTHORIZED] = "未授权"
	message[FORBIDDEN] = "权限不足"

	// 资源相关错误
	message[NOT_FOUND] = "资源未找到"
	message[ALREADY_EXISTS] = "资源已存在"
	message[RESOURCE_CONFLICT] = "资源冲突"

	// 服务相关错误
	message[SERVICE_UNAVAILABLE] = "服务不可用"
	message[GATEWAY_TIMEOUT] = "网关超时"
	message[INTERNAL_SERVER_ERR] = "内部服务器错误"

	// 用户服务错误
	message[USER_NOT_FOUND] = "用户不存在"
	message[USER_ALREADY_EXISTS] = "用户已存在"
	message[INVALID_CREDENTIALS] = "无效凭证"
	message[UNAUTHORIZED_ACCESS] = "未授权访问"
	message[FORBIDDEN_OPERATION] = "禁止的操作"
	message[INTERNAL_SERVER_ERROR] = "内部服务器错误"
	message[NETWORK_TIMEOUT] = "网络超时"
	message[RATE_LIMIT_EXCEEDED] = "请求频率超出限制"

	// 注册相关错误码（新增）
	message[REGISTER_FAILED] = "注册失败"
	message[INVALID_INVITATION_CODE] = "无效邀请码"
	message[EMAIL_ALREADY_REGISTERED] = "邮箱已被注册"
	message[PHONE_ALREADY_REGISTERED] = "手机号已被注册"
	message[USERNAME_TAKEN] = "用户名已被占用"
	message[REGISTRATION_RATE_LIMITED] = "注册频率超出限制"
}

type CodeError struct {
	Code int         `json:"code" xml:"code"`
	Msg  string      `json:"msg" xml:"msg"`
	Data interface{} `json:"data" xml:"data"`
}

func (e CodeError) Error() string {
	return e.Msg
}

func NewCodeError(code int, msg string) *CodeError {
	return &CodeError{Code: code, Msg: msg}
}
func NewCodeErrorData(code int, msg string, data interface{}) *CodeError {
	return &CodeError{Code: code, Msg: msg, Data: data}
}

// 错误码映射
func MapErrorCode(err string) *CodeError {
	msg := message[err]
	if msg != "" {
		return NewCodeError(400, msg)
	} else {
		return NewCodeError(400, "系统错误")
	}
}

func MapErrorCodeString(str string) string {
	return message[str]
}
